class ListNode(object):
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next


def removeElements(head: ListNode, val: int) -> ListNode:
    # 定义新的链表头部，指向原来的头部，这样头部移动的时候不至于原链表元素消失
    result = ListNode(0)
    result.next = head
    # 定义前节点和当前节点
    prev, cur = result, head
    # 当前节点存在
    while cur:
        # 判断当前节点的值是否为val
        if cur.val == val:
            prev.next = cur.next  # 是删除当前节点(将前节点的next指向当前节点的next)
        else:
            prev = cur  # 否则 前节点后移到当前节点
        cur = cur.next  # 当前节点后移到下一节点
    return result.next  # 返回


node = ListNode(1)
node.next = ListNode(2)
node.next.next = ListNode(4)
removeElements(node, 4)
print(node.next.val)  # 2
print(node.next.next)  # None
